package com.alogic.commonmark.reattr;

import com.anysoft.util.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.AttributeProviderContext;
import org.commonmark.renderer.html.AttributeProviderFactory;
import org.commonmark.renderer.html.HtmlRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 * ReAttributeExtension
 * @since 1.6.13.11 [20200901 duanyy]
 */
public class ReAttributeExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, XMLConfigurable, Configurable {

    /**
     * logger of slf4j
     */
    protected final Logger LOG = LoggerFactory.getLogger(ReAttributeExtension.class);

    /**
     * 插件列表
     */
    protected List<AttributeProvider> providers = new ArrayList<AttributeProvider>();

    @Override
    public void configure(Properties p) {

    }

    @Override
    public void configure(Element root, Properties p) {
        XmlElementProperties props = new XmlElementProperties(root,p);
        configure(props);

        Factory<AttributeProvider> f = new Factory<AttributeProvider>();
        NodeList nodeList = XmlTools.getNodeListByPath(root,"on-tag");
        for (int i = 0 ; i < nodeList.getLength() ; i ++){
            Node node = nodeList.item(i);
            if (Node.ELEMENT_NODE != node.getNodeType()){
                continue;
            }
            Element elem = (Element)node;
            try{
                AttributeProvider provider = f.newInstance(elem,props,"module",ReAttributeProvider.class.getName());
                if (provider != null){
                    providers.add(provider);
                }
            }catch (Exception ex){
                LOG.warn("Can not create attribute provider:" + XmlTools.node2String(elem));
            }
        }
    }

    @Override
    public void extend(Parser.Builder builder) {
        // nothing to do
    }

    @Override
    public void extend(HtmlRenderer.Builder builder) {
        for (final AttributeProvider provider:providers){
            builder.attributeProviderFactory(new AttributeProviderFactory() {
                @Override
                public AttributeProvider create(AttributeProviderContext context) {
                    return provider;
                }
            });
        }
    }
}
